//
//  MainWindowDelegate.m
//  Mobile P2P
//
//  Created by Chris Karr on 5/20/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "MainWindowDelegate.h"

#import "NetworkTransport.h"

#define FIELD @"field"
#define OPERATOR @"operator"
#define VALUE @"value"

@implementation MainWindowDelegate

- (void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadComplete:) name:FILE_DOWNLOADED object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processResults:) name:SEARCH_RESULTS object:nil];
}

- (void) processResults:(NSNotification *) theNote
{
	NSArray * newResults = [[theNote userInfo] valueForKey:RESULTS];
	
	[results addObjects:newResults];
}

- (void) downloadComplete:(NSNotification *) theNote
{
	NSLog (@"download done. launch?");
}

- (IBAction) search:(id) sender
{
	[results removeObjects:[results arrangedObjects]];
	
	NSString * value = [[NSUserDefaults standardUserDefaults] stringForKey:VALUE];
	
	NSString * field = [[NSUserDefaults standardUserDefaults] stringForKey:FIELD];
	NSString * queryField = @"kMDItemMusicalGenre";
	
	if ([field isEqualToString:@"Genre"])
		queryField = @"kMDItemMusicalGenre";
	else if ([field isEqualToString:@"Kind"])
		queryField = @"kMDItemKind";
	else
		queryField = @"kMDItemFSName";

	NSString * operator = [[NSUserDefaults standardUserDefaults] stringForKey:OPERATOR];
	NSString * queryOperator = @"==";
	
	if ([operator isEqualToString:@"Contains"])
		value = [NSString stringWithFormat:@"*%@*", value, nil];
	
	NSString * queryString = [NSString stringWithFormat:@"%@ %@ \"%@\"c", queryField, queryOperator, value, nil];
	
	NSDictionary * query = [NSDictionary dictionaryWithObject:queryString forKey:QUERY];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:DO_SEARCH object:self userInfo:query];
}

- (IBAction) download:(id) sender
{
	NSDictionary * result = [[results selectedObjects] lastObject];

	if ([result valueForKey:DATA] == nil)
		[[NSNotificationCenter defaultCenter] postNotificationName:DOWNLOAD_FILE object:self userInfo:result];
	else
		NSLog (@"file already downloaded");
}

@end
